package com.hmall.cart.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.RandomUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.api.client.ItemClient;
import com.hmall.cart.config.CartProperties;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.common.utils.UserContext;
import com.hmall.cart.domain.dto.CartFormDTO;
import com.hmall.api.dto.ItemDTO;
import com.hmall.cart.domain.po.Cart;
import com.hmall.cart.domain.vo.CartVO;
import com.hmall.cart.mapper.CartMapper;
import com.hmall.cart.service.ICartService;

import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpMethod;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单详情表 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {


    private final ItemClient itemClient;
    private final CartProperties cartProperties;


    @Override
    public void addItem2Cart(CartFormDTO cartFormDTO) {
        if(checkItemExists(cartFormDTO.getItemId(), UserContext.getUser())) {
            //1、添加过该商品，购买数量+1
            lambdaUpdate().setSql("num = num + 1")
                    .eq(Cart::getItemId, cartFormDTO.getItemId())
                    .eq(Cart::getUserId, UserContext.getUser())
                    .update();
        } else {
            //2、未添加过该商品，如果当前这个用户的购物车商品没有超过10个的话；可以新增一条购物车记录
            Integer count = lambdaQuery().eq(Cart::getUserId, UserContext.getUser()).count();
            if (count >= 10) {
                throw new BizIllegalException("购物车商品数量超过限制！");
            }
            Cart cart = BeanUtils.copyProperties(cartFormDTO, Cart.class);
            cart.setUserId(UserContext.getUser());
            save(cart);
        }
    }



    @Override
    public List<CartVO> queryMyCarts() {
        // 1.查询我的购物车列表
        //List<Cart> carts = lambdaQuery().eq(Cart::getUserId, 1).list();
        List<Cart> carts = lambdaQuery().eq(Cart::getUserId, UserContext.getUser()).list();
        if (CollUtils.isEmpty(carts)) {
            return CollUtils.emptyList();
        }

        // 2.转换VO
        List<CartVO> vos = BeanUtils.copyList(carts, CartVO.class);

        // 3.处理VO中的商品信息
        handleCartItems(vos);

        // 4.返回
        return vos;
    }

    private void handleCartItems(List<CartVO> vos) {
        // 1.获取商品id
        Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());

        // 2.查询商品
//        List<ItemDTO> items = null;
////获取注册列表中的service服务列表
//        List<ServiceInstance> instances = discoveryClient.getInstances("item-service");
//
//        //从注册中心选择一个服务示例
//        ServiceInstance serviceInstance = instances.get(RandomUtil.randomInt(instances.size()));
//        //可以从实例中获取服务实例的url
//        String itemUrl = serviceInstance.getUri() + "/items?ids={ids}";

        //String itemUrl = "http://localhost:8081/items?ids={ids}";
//        ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
//                itemUrl, // 请求路径
//                HttpMethod.GET, // 请求方式
//                null, // 请求实体
//                new ParameterizedTypeReference<List<ItemDTO>>() {
//                }, // 响应数据类型
//                Map.of("ids", CollUtils.join(itemIds, ",")) // 修改: 使用 String.join 替代 CollUtils.join
//        );
//
//        if (response.getStatusCode().is2xxSuccessful()) {
//            items = response.getBody();
//        }
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (CollUtils.isEmpty(items)) {
            return;
        }

        // 3.转为 id 到 item的map
        Map<Long, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));

        // 4.写入vo
        for (CartVO v : vos) {
            ItemDTO item = itemMap.get(v.getItemId());
            if (item == null) {
                continue;
            }
            v.setNewPrice(item.getPrice());
            v.setStatus(item.getStatus());
            v.setStock(item.getStock());
        }
    }

    @Override
    public void removeByItemIds(Collection<Long> itemIds) {
        // 1.构建删除条件，userId和itemId
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
        queryWrapper.lambda()
                .eq(Cart::getUserId, UserContext.getUser())
                .in(Cart::getItemId, itemIds);
        // 2.删除
        remove(queryWrapper);
    }

    private void checkCartsFull(Long userId) {
        int count = lambdaQuery().eq(Cart::getUserId, userId).count();
        if (count >= cartProperties.getMaxAmount()) {
            throw new BizIllegalException(StrUtil.format("用户购物车课程不能超过{}", cartProperties.getMaxAmount()));
        }
    }

    private boolean checkItemExists(Long itemId, Long userId) {
        int count = lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getItemId, itemId)
                .count();
        return count > 0;
    }
}
